import asyncio
import aiohttp


# 基本格式
# async def task():
# 	print('task')
# 	await asyncio.sleep(1)
# 	print('task done')
#
#
# asyncio.run(task())

# 基本异步函数
# async def hello(name):
#     print(f"Hello, {name}!")
#     await asyncio.sleep(1)  # 模拟耗时操作
#     print(f"Goodbye, {name}!")
#
# async def main():
#     await hello("Alice")
#     await hello("Bob")
#
# asyncio.run(main())



# 并发执行多个异步函数
# async def task(name, seconds):
#     print(f"任务 {name} 开始")
#     await asyncio.sleep(seconds)
#     print(f"任务 {name} 完成")
#     return f"{name} 的结果"
#
# async def main():
#     # 并发执行多个任务
#     results = await asyncio.gather(
#         task("A", 2),
#         task("B", 1),
#         task("C", 3)
#     )
#     print("所有任务完成:", results)
#
# asyncio.run(main())


# 异步请求
# async def main():
# 	async with aiohttp.ClientSession() as session:
# 		async with session.get('https://httpbin.org/get?page=1') as response:
# 			print(response.status)
# 			print(await response.json())
#
#
# asyncio.run(main())

# 执行多个异步请求
async def fetch(session,url):
	async with session.get(url) as response:
		return await response.json()

async def main():
	async with aiohttp.ClientSession() as session:
		r = await asyncio.gather(*[fetch(session,f'https://httpbin.org/get?page={i}') for i in range(1,10)])
		for j in r:
			print(j)
		
asyncio.run(main())





